<template>
  <div>
    <div
      class="-mt-46 h-[calc(100vh-15px)] custom-navbar-wrapper-f5f5f5 pt-46 flex flex-col"
    >
      <NormalTabs
        :tabs="CATEGORIES.map(item => ({ id: item.id, name: item.name }))"
        :active-id="activeCategoryId"
        :tab-class="tabsTypeOneClass"
        @update:active-id="activeCategoryId = $event"
      />
      <div
        ref="scrollContainer"
        class="scroll-view scroll-view--vertical hide-scrollbar flex-1"
      >
        <div ref="scrollContent" class="scroll-view__content pt-15">
          <!-- AI订单 -->
          <div v-if="activeCategoryId === 'platform'" class="mx-15">
            <div
              v-for="item in historyData[activeCategoryId].records"
              :key="item.id"
              class="mb-15 py-12 px-15 rounded-10 bg-white"
              @click="navigateTo('OrderDetails', item)"
            >
              <div class="flex items-center justify-between mb-8 text-13">
                <div class="font-bold leading-18">
                  【{{ COMBO_TYPE_MAP[item.comboType] }}】
                </div>
                <div
                  class="px-6 h-22 leading-22 rounded-4"
                  :class="{
                    'text-FF4A35 c-bg-FF4A35-10':
                      item.status === PAY_STATUS_ENUM.REFUND,
                    'text-4D00FF bg-E2E0FF':
                      item.status !== PAY_STATUS_ENUM.REFUND
                  }"
                >
                  {{ PAY_STATUS_MAP[item.status] }}
                </div>
              </div>
              <div class="flex pt-10 border-t-1 border-F5F5F5 border-solid">
                <van-image
                  :src="
                    item.rechargeProdCover ||
                    `${IMG_CDN_39}/member/ai_coin_cover.png`
                  "
                  class="w-100 h-100"
                  radius="10"
                />
                <div class="flex-1 w-0 ml-15">
                  <div class="flex items-start justify-between text-15">
                    <div class="break-all">{{ item.rechargeProdName }}</div>
                    <div class="font-bold ml-15">¥{{ item.payMoney }}</div>
                  </div>
                  <div
                    class="flex items-start justify-between mt-10 text-12 text-999999"
                  >
                    <div class="mr-55 leading-18">
                      体验包含{{
                        assetContentText(item.rechargeAssetInfoVoList)
                      }}
                    </div>
                    <div>x1</div>
                  </div>
                </div>
              </div>
              <div class="text-right text-13">
                <span class="mr-4">实付金额</span>
                <span class="text-FF4A35 font-bold">¥</span>
                <template v-if="payMoneySplit(item.payMoney).decimalPart">
                  <span class="text-20 text-FF4A35 font-bold">{{
                    payMoneySplit(item.payMoney).integerPart
                  }}</span>
                  <span class="text-FF4A35 font-bold"
                    >.{{ payMoneySplit(item.payMoney).decimalPart }}</span
                  >
                </template>
                <template v-else>
                  <span class="text-20 text-FF4A35 font-bold">{{
                    payMoneySplit(item.payMoney).integerPart
                  }}</span>
                </template>
              </div>
            </div>
          </div>

          <!-- 其他渠道 -->
          <div v-if="activeCategoryId === 'channels'" class="mx-15">
            <div
              v-for="item in historyData[activeCategoryId].records"
              :key="item.id"
              class="mb-15 rounded-10 overflow-hidden"
              @click="navigateTo('OrderDetails', item)"
            >
              <div class="py-12 px-15 bg-white">
                <div class="flex items-center justify-between mb-8 text-13">
                  <div class="leading-18">该课程用于权益兑换</div>
                  <div
                    class="px-6 h-22 leading-22 rounded-4"
                    :class="{
                      'text-FF4A35 c-bg-FF4A35-10':
                        item.status === PAY_STATUS_ENUM.REFUND,
                      'text-4D00FF bg-E2E0FF':
                        item.status !== PAY_STATUS_ENUM.REFUND
                    }"
                  >
                    {{ PAY_STATUS_MAP[item.status] }}
                  </div>
                </div>
                <div class="flex pt-10 border-t-1 border-F5F5F5 border-solid">
                  <van-image
                    :src="item.channelProdCover"
                    class="w-100 h-100"
                    radius="10"
                  />
                  <div class="flex-1 w-0 ml-15">
                    <div class="flex items-start justify-between text-15">
                      <div class="break-all">{{ item.channelProdName }}</div>
                      <div class="font-bold ml-15">¥{{ item.price }}</div>
                    </div>
                    <div class="mt-6 text-13 text-999999 text-right">
                      <div>x{{ item.quantity }}</div>
                    </div>
                  </div>
                </div>
                <div class="flex items-center mt-12 text-13 leading-18">
                  <div
                    v-if="item.channelType === CHANNEL_ENUM.WX_VIDEO"
                    class="flex items-center"
                  >
                    <span>下单渠道：</span>
                    <svg-icon
                      name="icon-shipinhao"
                      :size="16"
                      color="#FA9D3B"
                    />
                    <span class="ml-4">视频号</span>
                  </div>
                  <div class="ml-auto">
                    <span class="mr-4">实付金额</span>
                    <span class="text-FF4A35 font-bold">¥</span>
                    <template v-if="payMoneySplit(item.payMoney).decimalPart">
                      <span class="text-20 text-FF4A35 font-bold">{{
                        payMoneySplit(item.payMoney).integerPart
                      }}</span>
                      <span class="text-FF4A35 font-bold"
                        >.{{ payMoneySplit(item.payMoney).decimalPart }}</span
                      >
                    </template>
                    <template v-else>
                      <span class="text-20 text-FF4A35 font-bold">{{
                        payMoneySplit(item.payMoney).integerPart
                      }}</span>
                    </template>
                  </div>
                </div>
              </div>
              <div class="order-gifts pt-22 pb-15 px-15">
                <div class="pt-12 pb-15 px-15 rounded-10 bg-F5F5F5">
                  <div class="text-13">
                    可<span class="text-with-underline">兑换权益</span
                    >具体内容如下：
                  </div>
                </div>
                <div class="flex mt-12">
                  <div class="relative w-100 h-100 rounded-10 overflow-hidden">
                    <van-image
                      :src="
                        item.rechargeProdCover ||
                        `${IMG_CDN_39}/member/ai_coin_cover.png`
                      "
                      class="w-100 h-100"
                      radius="10"
                    />
                    <div
                      class="absolute bottom-0 right-0 px-6 h-22 leading-22 text-13 text-white rounded-tl-10 c-translucent-balck50"
                    >
                      {{ COMBO_TYPE_MAP[item.comboType] }}
                    </div>
                  </div>
                  <div class="flex-1 w-0 ml-15">
                    <div class="text-15 break-all">
                      {{ item.rechargeProdName }}
                    </div>
                    <div class="mt-10 text-12 text-999999 leading-18">
                      体验包含{{
                        assetContentText(item.rechargeAssetInfoVoList)
                      }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="isLoading" class="py-20 flex justify-center items-center">
            <van-loading size="24px" vertical>
              <span class="text-13 text-999 mt-10">加载中...</span>
            </van-loading>
          </div>

          <!-- 没有更多数据 -->
          <div
            v-if="
              isFinished && historyData[activeCategoryId].records.length > 0
            "
            class="py-15 text-center text-13 text-999"
          >
            <span class="inline-block px-10 py-5 rounded-full bg-gray-100"
              >没有更多数据了</span
            >
          </div>
          <!-- 空状态 -->
          <EmptyState
            v-if="
              !isLoading && historyData[activeCategoryId].records.length === 0
            "
            class="mt-50"
          />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, watch, nextTick, onBeforeUnmount } from "vue";
import NormalTabs from "@/components/NormalTabs/index.vue";
import type { PageResponse } from "src/types";
import {
  ASSET_TYPE_MAP,
  COMBO_TYPE_MAP,
  IMG_CDN_39,
  PAY_STATUS_MAP
} from "@/constants";
import { showToast } from "vant";
import {
  ChannelRechargeOrdersInfoData,
  getChannelRechargeOrders,
  getRechargeOrders,
  RechargeAssetInfoData,
  RechargeOrdersInfoData
} from "@/api/OrderList";
import { CHANNEL_ENUM, PAY_STATUS_ENUM } from "@/enums";
import router from "@/router";
import { payMoneySplit } from "@/utils";

defineOptions({
  name: "OrderList"
});
// 跳转页面
const navigateTo = (
  routeName: string,
  params: RechargeOrdersInfoData | ChannelRechargeOrdersInfoData
) => {
  router.push({
    name: routeName,
    params: {
      id:
        activeCategoryId.value === "platform"
          ? (params as RechargeOrdersInfoData).id
          : (params as ChannelRechargeOrdersInfoData).orderId,
      orderType: activeCategoryId.value
    }
  });
};

// 获取资产内容
const assetContentText = (assetTypeList: RechargeAssetInfoData[]): string => {
  const assetContentArr = [];
  for (let item of assetTypeList) {
    assetContentArr.push(
      `${ASSET_TYPE_MAP[item.assetType]}${item.assetAmount}个`
    );
  }
  return assetContentArr.join("；");
};

// 分类配置
const CATEGORIES = [
  { id: "platform", name: "AI订单", api: getRechargeOrders },
  { id: "channels", name: "其他渠道", api: getChannelRechargeOrders }
];
const activeCategoryId = ref<string>("platform");

// 样式配置
const tabsTypeOneClass = ref({
  justifyContent: "justify-around",
  itemWidth: "w-140"
});

// 统一历史记录数据
const historyData = ref<Record<string, PageResponse<any>>>({
  platform: { current: 1, pages: 0, records: [], size: 24, total: 0 },
  channels: { current: 1, pages: 0, records: [], size: 24, total: 0 }
});

// 加载状态
const isLoading = ref(false);
const isFinished = ref(false);

// 滚动容器引用
const scrollContainer = ref<HTMLElement | null>(null);
const scrollContent = ref<HTMLElement | null>(null);

// 统一加载函数
const loadHistoryData = async (loadMore = false) => {
  if (isLoading.value) return;

  try {
    isLoading.value = true;
    const category = activeCategoryId.value;
    const currentData = historyData.value[category];

    const nextPage = loadMore ? currentData.current + 1 : 1;
    const params = { pageNo: nextPage, pageSize: 24 };

    const apiFunc = CATEGORIES.find(c => c.id === category)?.api;
    if (!apiFunc) return;

    const res = await apiFunc(params);

    historyData.value[category] = loadMore
      ? { ...res, records: [...currentData.records, ...res.records] }
      : res;

    isFinished.value = res.current >= res.pages;

    if (loadMore && res.records.length > 0) {
      showToast({
        message: `加载了 ${res.records.length} 条新记录`,
        position: "bottom"
      });
    }
  } catch (error) {
    console.error("加载失败:", error);
    showToast("加载失败，请稍后再试");
  } finally {
    isLoading.value = false;
    nextTick(() => {
      if (scrollContainer.value && scrollContent.value) {
        scrollContainer.value.addEventListener("scroll", handleScroll);
      }
    });
  }
};

// 监听分类切换
watch(activeCategoryId, newId => {
  // 移除旧分类的滚动监听
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
  }
  // 清空其他分类的数据
  const otherCategory = newId === "platform" ? "channels" : "platform";
  historyData.value[otherCategory] = {
    current: 1,
    pages: 0,
    records: [],
    size: 24,
    total: 0
  };
  // 加载新分类数据
  if (historyData.value[newId].records.length === 0) {
    loadHistoryData();
  }
});

// 处理滚动事件
const handleScroll = () => {
  if (
    !scrollContainer.value ||
    !scrollContent.value ||
    isLoading.value ||
    isFinished.value
  )
    return;

  const containerHeight = scrollContainer.value.clientHeight;
  const contentHeight = scrollContent.value.scrollHeight;
  const scrollTop = scrollContainer.value.scrollTop;
  const distanceToBottom = contentHeight - (scrollTop + containerHeight);

  if (distanceToBottom < 50) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
    loadHistoryData(true);
  }
};

onMounted(() => {
  // 初始加载当前分类数据
  loadHistoryData();
});

onBeforeUnmount(() => {
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
  }
});
</script>

<style scoped lang="less">
.order-gifts {
  position: relative;
  background-image:
    radial-gradient(circle at 10px 10px, transparent 10px, #ffffff 0),
    radial-gradient(
      circle at calc(100% - 10px) 10px,
      transparent 10px,
      #ffffff 0
    );
  background-position:
    -10px 0,
    calc(100% + 10px) 0;
  background-repeat: no-repeat;
}
.order-gifts::before {
  position: absolute;
  content: "";
  top: 10px;
  left: 12px;
  height: 0;
  width: calc(100% - 24px);
  border-bottom: 1px dashed #f5f5f5;
}
</style>
